package com.yunpuvip.sachet.rest.controller.port;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.yunpuvip.sachet.biz.entity.Player;
import com.yunpuvip.sachet.biz.entity.Sysparam;
import com.yunpuvip.sachet.biz.service.PlayerService;
import com.yunpuvip.sachet.biz.service.SysparamService;
import com.yunpuvip.sachet.modular.constant.ApplicationConstant;
import com.yunpuvip.sachet.modular.constant.response.ServerResponse;
import com.yunpuvip.sachet.modular.core.exception.GunsException;
import com.yunpuvip.sachet.modular.core.exception.RestServiceExceptionEnum;
import com.yunpuvip.sachet.modular.util.cache.CacheKit;
import com.yunpuvip.sachet.modular.util.sms.Sendsms;
import com.yunpuvip.sachet.rest.common.util.VerifyCodeKit;
import com.yunpuvip.sachet.rest.common.util.wxtool.WxTool;
import com.yunpuvip.sachet.rest.common.vo.LoginVo;
import com.yunpuvip.sachet.rest.common.vo.PlayerVo;
import com.yunpuvip.sachet.rest.common.vo.WeChatUser;
import com.yunpuvip.sachet.rest.config.properties.JwtProperties;
import com.yunpuvip.sachet.rest.controller.common.RestBaseController;
import com.yunpuvip.sachet.rest.modular.auth.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * @ auther wushaohong
 * @ date  2019/8/10
 **/
@RequestMapping("login")
@RestController
@Slf4j

public class LoginController extends  RestBaseController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private SysparamService sysparamService;

    @Autowired
    PlayerService playerService;

    @Autowired
    private WxTool wxTool;

    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 公众号 授权获取( getCode )
     *
     * @return void
     * @author hyf
     * @date 2019-03-11
     */
    @RequestMapping("/openid")
    public void redirectToGetOpenidForce(HttpServletResponse response, String userNo, String qrcode) throws IOException {
        log.info("1,参数获取");
        String host = sysparamService.loadSetting("webhost").getParamValue();
        String appid = sysparamService.loadSetting("AppID").getParamValue();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(host).append("/member/login/getOpenid?");
        // 默认都会传
        log.info("2,参数已获取，开始拿Code");


       // stringBuilder.append("params=").append(qrcode).append("--").append(userNo);
        //String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + stringBuilder.toString() + "&response_type=code&scope=snsapi_userinfo#wechat_redirect";
        //微信静默授权
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+stringBuilder.toString()+"&response_type=code&scope=snsapi_base&state=123#wechat_redirect";


        System.out.println("待跳转的完整URL：" + url);
        log.info("3,跳转拿Code url：{}",url);
        response.sendRedirect(url);
    }
    /**
     * 公众号  获取授权用户信息
     * 用code换取oauth2的openid
     * 详情请见: http://mp.weixin.qq. com/wiki/1/8a5ce6257f1d3b2afb20f83e72b72ce9.html
     * 这代码。。醉了
     * @param code code
     */
    @RequestMapping(value = "/getOpenid")
    public void getOpenid(HttpServletResponse response
            , @RequestParam(value = "code") String code
            , String redirectUrll
          ) throws IOException {
        //, @RequestParam(value = "params") String params
        log.info("4.开始通过code 获取openid以及用户信息");
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxTool.getWxMpOAuth2AccessToken(code);
        //WeChatUser weChatUser = wxTool.getWeChatUserInfo(wxMpOAuth2AccessToken.getAccessToken(), wxMpOAuth2AccessToken.getOpenId());
        //静默授权没有以下信息
        System.out.println("获取到的用户信息：" + wxMpOAuth2AccessToken);

        Sysparam sysparam = sysparamService.loadSetting(ApplicationConstant.JUMPURL);
        if(ObjectUtil.isNull(sysparam)|| StrUtil.isEmpty(sysparam.getParamValue())){
            throw new GunsException(RestServiceExceptionEnum.JUMP_URL_ERROR);
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        String paramValue = sysparam.getParamValue();
        log.info("7.跳转地址:{}",paramValue);
        response.sendRedirect( paramValue.trim()+"?openId="+openId);
    }






    /**
     *
     * 短信验证登录
     * @param loginVo
     *
     * @return
     */
    @RequestMapping(value = "/auth")
    public ServerResponse playerLogin(@Valid LoginVo loginVo ){
        //String openid = loginVo.getOpenid();
        String phoneNumber = loginVo.getPhoneNumber();
        String verifyCode = loginVo.getVerifyCode();
        if(phoneNumber.equals("13512345678")){

        }else {
            //检查验证码
            boolean res = false;
            res = VerifyCodeKit.checkVerifyCode(loginVo.getPhoneNumber(), loginVo.getVerifyCode());
            if (!res) {
                return ServerResponse.creatByErrorEnum(RestServiceExceptionEnum.PHONE_CODE_NOT_MISMATCH);
            }
        }
        System.err.println("验证码无误") ;
        //生成token
        String token = jwtTokenUtil.getToken(phoneNumber);
        //查看号码是否已被绑定,绑定则返回用户基本信息
        Date tokenExpireTime = jwtTokenUtil.getTokenExpireTime();
        Player player = playerService.insertOrUpdateUser(phoneNumber,token,tokenExpireTime,loginVo.getName());
        PlayerVo playerVo = new PlayerVo();
        BeanUtil.copyProperties(player,playerVo);

        //将登录的用户信息缓存
       // CacheKit.put("player",token,playerVo);
        //返回信息给前端
        HashMap<String, Object> map = new HashMap<>();
        return  ServerResponse.creatBySuccess(playerVo);
    }



    @RequestMapping(value = "/noAuth")
    public ServerResponse noAuth(@RequestParam String phoneNumber ){
        //生成token
        String token = jwtTokenUtil.getToken(phoneNumber);
        //查看号码是否已被绑定,绑定则返回用户基本信息
        Long expiration = jwtProperties.getExpiration();
        final Long day = expiration / (24 * 3600);
        DateTime expireTime = DateUtil.offsetDay(new Date(), day.intValue());
        Player player = playerService.insertOrUpdateUser(phoneNumber,token,expireTime,"34343");
        PlayerVo playerVo = new PlayerVo();
        BeanUtil.copyProperties(player,playerVo);
        //将登录的用户信息缓存
       // CacheKit.put("player",token,playerVo);
        //返回信息给前端
        HashMap<String, Object> map = new HashMap<>();
        return  ServerResponse.creatBySuccess(playerVo);
    }



    /**
     * 发送用户验证码
     * @param phoneNumber
     *     REGISTER(1, "注册"),
     *     UPDATEPASSWORD(2, "修改密码"),
     *     VALIDNO(3, "通用验证码");
     * @return
     */
    @RequestMapping(value = "/verifyCode")
    public ServerResponse getVerifyCode(@RequestParam String phoneNumber, @RequestParam(required = false,defaultValue = "1")  Integer sendType){
        //获取短信验证码
        String code = Sendsms.sendSmsCodeCommon(phoneNumber, sendType);
        HashMap<String,String> map = new HashMap<>();
        //缓存验证码
        VerifyCodeKit.putVerifyCode(phoneNumber,code);
        return ServerResponse.creatBySuccessMessage("短信验证码发送成功");
    }

    @RequestMapping("testTwo")
    public String testTwo( ) {
        playerService.testEX();
            return  "ok";
    }
    @RequestMapping("testString")
    public String testString ( ) {
        String genUserNo = playerService.genUserNo();
        return  genUserNo;
    }

}
